package com.hyperfix.washer.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyperfix.models.washer.pojos.ParamConfig;
import com.hyperfix.washer.mapper.ParamConfigMapper;
import com.hyperfix.washer.mapper.PipelineMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JiangChunYu
 * 2024/4/25
 */
@Slf4j
@Component
public class ParamConfigRegistrar implements CommandLineRunner {
    @Resource
    private PipelineMapper pipelineMapper;
    @Resource
    private ParamConfigMapper paramConfigMapper;

    private static final Map<Integer, Map<String, ParamConfig>> PARAM_CONFIG_MAP = new HashMap<>();

    @Override
    public void run(String... args) {
        loadParamConfig();
    }

    public Map<String,ParamConfig> getConfigParamMap(Integer pipelineId) {
        return PARAM_CONFIG_MAP.get(pipelineId);
    }

    public void modifyParamConfig(ParamConfig paramConfig) {
        Integer pipelineId = paramConfig.getPipelineId();
        Map<String, ParamConfig> paramConfigMap = PARAM_CONFIG_MAP.get(pipelineId);
        // 该管线无任何参数配置
        if (paramConfigMap == null) {
            paramConfigMap = new HashMap<>();
            paramConfigMap.put(paramConfig.getType(), paramConfig);
            PARAM_CONFIG_MAP.put(pipelineId, paramConfigMap);
            return;
        }
        paramConfigMap.put(paramConfig.getType(), paramConfig);
    }

    /**
     * 加载参数配置
     */
    private void loadParamConfig() {
        List<Integer> pipelineIds = pipelineMapper.selectIdList();
        pipelineIds.forEach(pipelineId -> {
            List<ParamConfig> paramConfigs = paramConfigMapper.selectList(new LambdaQueryWrapper<ParamConfig>().eq(ParamConfig::getPipelineId, pipelineId));
            Map<String, ParamConfig> paramConfigMap = new HashMap<>();
            paramConfigs.forEach(paramConfig -> paramConfigMap.put(paramConfig.getType(), paramConfig));
            PARAM_CONFIG_MAP.put(pipelineId, paramConfigMap);
        });
        log.info("参数配置加载完毕...");
    }
}
